﻿using Blm.VisionCloud.FrameWork.Utility;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using VisionCloud.Domain.Common;
using VisionCloud.Domain.DtoModel.Ms;
using VisionCloud.Utility;

namespace VisionCloud.Service.Demo
{
    public class ExternalWallService
    {
        /// <summary>
        /// 外立面项目数据目录
        /// </summary>
        private readonly string externalDataDir = $"{ConfigHelper.GetValue<string>("TaskResultData")}/msdata";

        public ApiPageResult<string> GetProjectName(PageRequest request)
        {
            var projectDirs = Directory.GetDirectories(externalDataDir).Select(x => Path.GetFileName(x)).Where(x => x != "temp");
            var total = projectDirs.Count();
            var skip = request.PageSize * (request.Page - 1);
            var res = projectDirs.Where(x => string.IsNullOrWhiteSpace(request.Keywords) || x.Contains(request.Keywords));
            if (request.IsAscend)
                res = res.OrderBy(x => x);
            else
                res = res.OrderByDescending(x => x);

            return new ApiPageResult<string> { CurrentPage = request.Page, Total = total, PageData = res.Skip(skip).Take(request.PageSize).ToList(), TotalPage = (int)Math.Ceiling(total * 1.0 / request.PageSize) };
        }

        public async ValueTask<bool> UploadFile(IFormFile file)
        {
            try
            {
                #region 保存zip文件

                var fileName = file.FileName;

                if (Path.GetExtension(fileName) != ".zip") throw new Exception("只支持zip文件");
                var projectName = Path.GetFileNameWithoutExtension(fileName).Split('-')[0];
                if (string.IsNullOrEmpty(projectName)) throw new Exception("文件名称不符合规范");
                if (!Directory.Exists(externalDataDir)) Directory.CreateDirectory(externalDataDir);
                var tempSaveDir = $"{externalDataDir}/temp";
                if (!Directory.Exists(tempSaveDir)) Directory.CreateDirectory(tempSaveDir);
                var tempSaveFileFullPath = $"{tempSaveDir}/{fileName}";
                if (File.Exists(tempSaveFileFullPath)) File.Delete(tempSaveFileFullPath);
                using FileStream stream = new FileStream(tempSaveFileFullPath, FileMode.CreateNew);
                await file.CopyToAsync(stream);
                stream.Close();

                #endregion 保存zip文件

                var taskName = Path.GetFileNameWithoutExtension(fileName);
                var extractPath = $"{externalDataDir}/{projectName}/{taskName}";
                var msg = FileInfoUtil.ExtractToDirectory(tempSaveFileFullPath, extractPath, true);
                var dirs = Directory.GetDirectories(extractPath);
                var dirNames = dirs.Select(x => Path.GetFileName(x));
                if (!dirNames.Contains("3D") && dirNames.Contains(taskName))
                {
                    var tempMoveDir = $"{extractPath}_temp";
                    var taskDir = Path.Combine(extractPath, taskName);
                    var dir = Path.Combine(taskDir, "3D");
                    if (Directory.Exists(dir))
                    {
                        if (Directory.Exists(tempMoveDir)) Directory.Delete(tempMoveDir, true);
                        Directory.Move(taskDir, tempMoveDir);
                        Directory.Delete(extractPath, true);
                        Directory.Move(tempMoveDir, extractPath);
                        if (Directory.Exists(tempMoveDir)) Directory.Delete(tempMoveDir);
                    }
                }

                File.Delete(tempSaveFileFullPath);
                return true;
            }
            catch (Exception ex)
            {
                Logger.Error(string.Format("上传外立面数据出错，{0}", ex.Message), ex);
                return false;
            }
        }

        public ApiPageResult<ProjectReportDto> GetTaskName(QueryReportByproject request)
        {
            var projectDir = Path.Combine(externalDataDir, request.ProjectName);
            var skip = request.PageSize * (request.Page - 1);
            var list = Directory.GetDirectories(projectDir).Where(x => string.IsNullOrWhiteSpace(request.Keywords) || Path.GetFileName(x).Contains(request.Keywords)).ToList();
            var total = list.Count;
            var totalPage = (int)Math.Ceiling(total * 1.0 / request.PageSize);

            var reports = new List<ProjectReportDto>();
            list.ForEach(x =>
            {
                var name = Path.GetFileName(x);
                var dirInfo = new DirectoryInfo(x);
                reports.Add(new ProjectReportDto { TaskName = name, UploadDate = dirInfo.CreationTime });
            });
            if (request.IsAscend) reports = reports.OrderBy(x => x.UploadDate).Skip(skip).Take(request.PageSize).ToList();
            else reports = reports.OrderByDescending(x => x.UploadDate).Skip(skip).Take(request.PageSize).ToList();
            return new ApiPageResult<ProjectReportDto>()
            {
                Total = total,
                TotalPage = totalPage,
                CurrentPage = request.Page,
                PageData = reports
            };
        }

        public bool DeleteReports(DeleteTaskDataDto dto)
        {
            try
            {
                var projectDir = Path.Combine(externalDataDir, dto.ProjectName);
                dto.TaskNames.ForEach(x =>
                {
                    var taskDir = Path.Combine(projectDir, x);
                    if (Directory.Exists(taskDir)) Directory.Delete(taskDir, true);
                });
                return true;
            }
            catch (Exception ex)
            {
                Logger.Error(string.Format("删除{0}项目的任务数据出错，{1}", dto.ProjectName, ex.Message), ex);
                return false;
            }
        }

        public ExternalWallDataDetail GetDetail(ProjectTaskName dto)
        {
            var fileServer = $"{ConfigHelper.GetValue<string>("FileServer")}/taskresult/msdata/{dto.ProjectName}/{dto.TaskName}";
            var jsonPath = $"{fileServer}/3D";
            return new ExternalWallDataDetail
            {
                TaskReportUrl = $"{fileServer}/测量报告.pdf",
                ElementsJsonUrl = $"{jsonPath}/exteralwallElements.json",
                FlatnessJsonUrl = $"{jsonPath}/flatness.json",
                VerticalJsonUrl = $"{jsonPath}/vertical.json",
            };
        }
    }
}